package DianShang_2024.ds_02.indicator

import org.apache.hudi.DataSourceWriteOptions.{PARTITIONPATH_FIELD, PRECOMBINE_FIELD, RECORDKEY_FIELD}
import org.apache.hudi.QuickstartUtils.getQuickstartWriteConfigs
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions.col

object indicator03 {
  def main(args: Array[String]): Unit = {
    /*
        根据dwd_ds_hudi库中的表统计每个省每月下单的数量和下单的总金额，并按照year，month，region_id进行分组,按照total_amount逆序排序，形
        成sequence值，将计算结果存入Hudi的dws_ds_hudi数据库province_consumption_day_aggr表中（表结构如下），然后使用spark-shell根据
        订单总数、订单总金额、省份表主键均为降序排序，查询出前5条，在查询时对于订单总金额字段将其转为bigint类型（避免用科学计数法展示），将SQL语句
        复制粘贴至客户端桌面【Release\任务B提交结果.docx】中对应的任务序号下，将执行结果截图粘贴至客户端桌面【Release\任务B提交结果.docx】中对
        应的任务序号下
     */
    val spark=SparkSession.builder()
      .master("local[*]")
      .appName("指标计算第二题")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

    val order_info_path="hdfs://192.168.40.110:9000/user/hive/warehouse/dwd_ds_hudi02.db/fact_order_info"
    val province_path="hdfs://192.168.40.110:9000/user/hive/warehouse/dwd_ds_hudi02.db/dim_province"
    val region_path="hdfs://192.168.40.110:9000/user/hive/warehouse/dwd_ds_hudi02.db/dim_region"


    val temp01=spark.read.format("hudi").load(order_info_path)
    temp01.createOrReplaceTempView("temp01")
    spark.read.format("hudi").load(order_info_path)
      .where("etl_date=(select max(etl_date) from temp01)")
      .dropDuplicates()
      .createOrReplaceTempView("order_info")


    val temp02=spark.read.format("hudi").load(province_path)
    temp02.createOrReplaceTempView("temp02")
    spark.read.format("hudi").load(province_path)
      .where("etl_date=(select max(etl_date) from temp02)")
      .dropDuplicates()
      .createOrReplaceTempView("province")

    val temp03 = spark.read.format("hudi").load(region_path)
    temp03.createOrReplaceTempView("temp03")
    spark.read.format("hudi").load(region_path)
      .where("etl_date=(select max(etl_date) from temp03)")
      .dropDuplicates()
      .createOrReplaceTempView("region")


    val result=spark.sql(
      """
        |select
        |uuid() as uuid,
        |t1.province_id,
        |t2.name as province_name,
        |t3.id as region_id,
        |t3.region_name ,
        |sum(t1.final_total_amount) as total_amount,
        |count(*) as total_count,
        |row_number() over(partition by substr(t1.create_time,1,4),substr(t1.create_time,5,2),t3.id order by sum(t1.final_total_amount) desc ) as sequence,
        |substr(t1.create_time,1,4) as year,
        |substr(t1.create_time,5,2) as month
        |from order_info as t1
        |join province as t2
        |on t2.id=t1.province_id
        |join region as t3
        |on t3.id=t2.region_id
        |group by t3.id,t3.region_name,t1.province_id,t2.name,substr(t1.create_time,1,4),substr(t1.create_time,5,2)
        |""".stripMargin)



    //  创建表
    spark.sql("use dws_ds_hudi02")
    spark.sql("drop table if exists province_consumption_day_aggr")
    spark.sql(
      """
        |create table if not exists province_consumption_day_aggr(
        |uuid String,
        |province_id int,
        |province_name String,
        |region_id int,
        |region_name  String,
        |total_amount double,
        |total_count int,
        |sequence int,
        |year int,
        |month int
        |)using hudi
        |tblproperties(
        |type="cow",
        |primaryKey="uuid",
        |preCombineField="total_count",
        |hoodie.datasource.hive_aync.mode="hms"
        |)
        |partitioned by(year,month)
        |""".stripMargin)

    result.withColumn("total_amount",col("total_amount").cast("double"))
      .withColumn("year",col("year").cast("int"))
      .withColumn("month",col("month").cast("int"))
      .write.mode("append")
      .format("hudi")
      .options(getQuickstartWriteConfigs)
      .option(RECORDKEY_FIELD.key(),"uuid")
      .option(PRECOMBINE_FIELD.key(),"total_count")
      .option(PARTITIONPATH_FIELD.key(),"year,month")
      .option("hoodie.table.name","province_consumption_day_aggr")
      .save("hdfs://192.168.40.110:9000/user/hive/warehouse/dws_ds_hudi02.db/province_consumption_day_aggr")



    spark.close()
  }

}
